package com.example.mydy;

import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.mydy.api.UserApi;
import com.example.mydy.model.TaskDetailResponse;
import com.example.mydy.model.CommonResponse;
import com.example.mydy.model.Task;
import com.example.mydy.utils.NetworkUtils;
import java.util.HashMap;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import com.google.gson.Gson;
import android.util.Log;

public class TaskDetailActivity extends AppCompatActivity {
    private static final String TAG = "TaskDetailActivity";
    
    private TextView tvTaskTitle;
    private TextView tvTaskDescription;
    private TextView tvTaskReward;
    private TextView tvTaskStatus;
    private Button btnAcceptTask;
    private Button btnSubmitTask;
    
    private int taskId;
    private UserApi userApi;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_detail);
        
        taskId = getIntent().getIntExtra("task_id", -1);
        if (taskId == -1) {
            Toast.makeText(this, "任务ID无效", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        userApi = NetworkUtils.getUserApi();
        initViews();
        loadTaskDetail();
    }
    
    private void initViews() {
        tvTaskTitle = findViewById(R.id.tv_task_title);
        tvTaskDescription = findViewById(R.id.tv_task_description);
        tvTaskReward = findViewById(R.id.tv_task_reward);
        tvTaskStatus = findViewById(R.id.tv_task_status);
        btnAcceptTask = findViewById(R.id.btn_accept_task);
        btnSubmitTask = findViewById(R.id.btn_submit_task);
        
        btnAcceptTask.setOnClickListener(v -> acceptTask());
        btnSubmitTask.setOnClickListener(v -> submitTask());
    }
    
    private void loadTaskDetail() {
        String token = NetworkUtils.getAuthToken();
        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        userApi.getTaskDetail(token, taskId).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        // 处理任务详情数据
                        try {
                            Object data = response.body().getData();
                            // 将数据转换为Task对象
                            Gson gson = new Gson();
                            String json = gson.toJson(data);
                            Task task = gson.fromJson(json, Task.class);
                            displayTaskDetails(task);
                        } catch (Exception e) {
                            Log.e(TAG, "解析任务详情失败", e);
                            Toast.makeText(TaskDetailActivity.this, "加载任务详情失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(TaskDetailActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(TaskDetailActivity.this, "加载任务详情失败", Toast.LENGTH_SHORT).show();
                }
            }
            
            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                Toast.makeText(TaskDetailActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void displayTaskDetails(Task task) {
        if (task != null) {
            tvTaskTitle.setText(task.getTitle());
            tvTaskDescription.setText(task.getDescription());
            tvTaskReward.setText(String.format("奖励: ¥%.2f", task.getReward()));
            tvTaskStatus.setText(task.getStatus());
            
            // 根据任务状态更新按钮状态
            boolean canAccept = "未接受".equals(task.getStatus());
            boolean canSubmit = "进行中".equals(task.getStatus());
            
            btnAcceptTask.setEnabled(canAccept);
            btnSubmitTask.setEnabled(canSubmit);
        } else {
            Toast.makeText(this, "任务数据为空", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void updateUI(TaskDetailResponse taskDetail) {
        tvTaskTitle.setText(taskDetail.getTitle());
        tvTaskDescription.setText(taskDetail.getDescription());
        tvTaskReward.setText(String.format("奖励: ¥%.2f", taskDetail.getReward()));
        tvTaskStatus.setText(taskDetail.getStatus());
        
        // 根据任务状态更新按钮状态
        boolean canAccept = "未接受".equals(taskDetail.getStatus());
        boolean canSubmit = "进行中".equals(taskDetail.getStatus());
        
        btnAcceptTask.setEnabled(canAccept);
        btnSubmitTask.setEnabled(canSubmit);
    }
    
    private void acceptTask() {
        String token = NetworkUtils.getAuthToken();
        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }
        
        Map<String, String> data = new HashMap<>();
        data.put("taskId", String.valueOf(taskId));
        
        userApi.submitTask(token, data).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        Toast.makeText(TaskDetailActivity.this, "接受任务成功", Toast.LENGTH_SHORT).show();
                        loadTaskDetail(); // 刷新任务状态
                    } else {
                        Toast.makeText(TaskDetailActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(TaskDetailActivity.this, "接受任务失败", Toast.LENGTH_SHORT).show();
                }
            }
            
            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                Toast.makeText(TaskDetailActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void submitTask() {
        String token = NetworkUtils.getAuthToken();
        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }
        
        Map<String, String> data = new HashMap<>();
        data.put("taskId", String.valueOf(taskId));
        data.put("status", "completed");
        
        userApi.submitTask(token, data).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        Toast.makeText(TaskDetailActivity.this, "提交任务成功", Toast.LENGTH_SHORT).show();
                        loadTaskDetail(); // 刷新任务状态
                    } else {
                        Toast.makeText(TaskDetailActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(TaskDetailActivity.this, "提交任务失败", Toast.LENGTH_SHORT).show();
                }
            }
            
            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                Toast.makeText(TaskDetailActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}